package com.smy.baseutil.img;


import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.smy.baseutil.exception.ServiceException;


/**
 * 
* @ClassName: ImgCompressUtil  
* @Description: 图片压缩工具类  
* @author zhoutao 
* @date 2017年9月15日 上午9:40:20  
*
 */
public class ImgCompressUtil {
    
    private static Logger logger = LoggerFactory.getLogger(ImgCompressUtil.class);
    
    public static final String IMGSUFFIX = "_1";
    
    public static final int DEFAULT_SIZE = 160;

    /**
     * 强制压缩/放大图片到固定的大小
     *
     * @param w                int 新宽度
     * @param h                int 新高度
     * @param originalFilename String 图片url
     * @Param imgSuffix 图片格式（jpg,png,jpeg......）
     * @param fileSuffix 图片文件后缀
     * @return
     */
	public static Boolean resize(Integer w, Integer h, String originalFilename, String imgSuffix, String fileSuffix) {
		if (StringUtils.isBlank(originalFilename) || originalFilename.lastIndexOf(".") == -1) {
			throw new ServiceException("0001", "文件名为空或文件格式错误");
		}
		try {
			File file = new File(originalFilename);// 读入文件
			Image img = ImageIO.read(file); // 构造Image对象
			if (StringUtils.isBlank(imgSuffix)) {
				imgSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
			}
			String fileName = originalFilename.substring(0, originalFilename.lastIndexOf(".")) + fileSuffix + "."
					+ imgSuffix;
			File destFile = new File(fileName);
            return ImageIO.write(resize(w, h, img), imgSuffix, destFile);
		} catch (IOException e) {
			logger.error("图片压缩出错：{}", e);
			return Boolean.FALSE;
		}
	}

    /**
     * 等比压缩或者放大图片
     * @param w
     * @param h
     * @param originalFilename
     * @param imgSuffix
     * @param fileSuffix
     * @return
     */
	public static Boolean scaleResize(Integer w, Integer h, String originalFilename, String imgSuffix,
			String fileSuffix) {
		try {
			File file = new File(originalFilename);// 读入文件
			Image img = ImageIO.read(file);
			int originalHeight = img.getHeight(null);
			int originalWidth = img.getWidth(null);
			float scale = 0.0f;
			if ((float) w / h != (float) originalWidth / originalHeight) {
				scale = (float) w / originalWidth < (float) h / originalHeight ? (float) h / originalHeight
						: (float) w / originalWidth;
				return scaleResize(scale, originalFilename, imgSuffix, fileSuffix);
			} else {
				return resize(w, h, originalFilename, imgSuffix, fileSuffix);
			}
		} catch (IOException e) {
			logger.error("图片压缩出错：{}", e);
			return Boolean.FALSE;
		}
	}
	
    /**
     * 按照比例系数压缩图片
     * @param scale
     * @param originalFilename
     * @param imgSuffix
     * @param fileSuffix
     * @return 
     */
	public static Boolean scaleResize(float scale, String originalFilename, String imgSuffix, String fileSuffix) {
		try {
			File file = new File(originalFilename);// 读入文件
			Image img = ImageIO.read(file);
			int originalHeight = img.getHeight(null);
			int originalWidth = img.getWidth(null);
			return resize((int) (originalWidth * scale), (int) (originalHeight * scale), originalFilename, imgSuffix,
					fileSuffix);
		} catch (IOException e) {
			logger.error("图片压缩出错：{}", e);
			return Boolean.FALSE;
		}

	}

	/**
	 * SCALE_SMOOTH 的缩略算法 <br>
	 * 生成缩略图片的平滑度的 优先级比速度高 <br>
	 * 生成的图片质量比较好 但速度慢
	 * @param w
	 * @param h
	 * @param img
	 * @return
	 */
    private static  BufferedImage resize(Integer w, Integer h, Image img){
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        image.getGraphics().drawImage(img.getScaledInstance(w, h,  Image.SCALE_SMOOTH), 0, 0,  null);
        return  image;      
    }
    
    /**
	 * 调整图片的尺寸
	 * 
	 * @param scale
	 * @param originalFilename
	 * @return
	 */
	public static Boolean scaleResize(String originalFilename) {
		try {
			File file = new File(originalFilename);// 读入文件
			Image img = ImageIO.read(file);
			int originalHeight = img.getHeight(null);
			int originalWidth = img.getWidth(null);

			String type = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

			if (Math.max(originalHeight, originalWidth) <= DEFAULT_SIZE) {
				return scaleResize(originalWidth, originalHeight, originalFilename, type, IMGSUFFIX);
			}

			return scaleResize(DEFAULT_SIZE, DEFAULT_SIZE, originalFilename, type, IMGSUFFIX);
		} catch (Exception e) {
			logger.error("图片压缩出错：{}", e);
			return Boolean.FALSE;
		}
	}
	
	
	/**
	 * 获取图片对象
	 * @param originalFilename
	 * @return
	 */
	public static BufferedImage getImage(String originalFilename) {
		try {
			File file = new File(originalFilename);// 读入文件
			return ImageIO.read(file);
		} catch (Exception e) {
			logger.error("获取图片信息出错：{}", e);
			return null;
		}
	}
    
}
